package icselab.appmodule.service;


import java.sql.ResultSet;
import java.sql.SQLException;

import icselab.appmodule.server.ServerManager;
import icselab.dbaccess.DeployDAO;
import icselab.dbaccess.MonitorDAO;
import icselab.util.ConfigParser;

public class MonitorService extends Thread{
	
	private static final String WEBMODULE = "WebModule";
	private boolean stopped = false;
	private boolean updating = false;

//	private String getServletStat(String moduleName, int index){
//		ServerManager smg = new ServerManager();
//		Stats stat = smg.getServerStat(WEBMODULE, moduleName, index);
//		Statistic[] statistics = stat.getStatistics();
//		return statistics[0].toString();
//	}
	
	//update monitoring statistics to database 
	private void updateStat(){
		ServerManager smg = new ServerManager();
		MonitorDAO mda = new MonitorDAO();
		DeployDAO dda = new DeployDAO();
		ResultSet rs = dda.getRunningInstance();
		//read instance names from DB result set and check monitoring data
		try {
			while(rs.next() && !stopped)
			{
				this.updating = true;
				String instId = rs.getString("InstanceId");
				String instName = rs.getString("InstanceName");
				String[] statList = smg.getServerStat(WEBMODULE, instName);			
				//System.out.println("Updating monitoring statistics of instance: "+instId);
				for(int i=0;i<statList.length;i++)
				{
					//parse monitor statistics string and split these figures
					String monitorString = statList[i].replace(':', ',');
					String[] infos = monitorString.split(",");
					
					int count = (infos[1].length()>15 ? 0 : Integer.parseInt(infos[1].trim()));
					int min = (infos[3].length()>15 ? 0 : Integer.parseInt(infos[3].trim()));
					int max = (infos[5].length()>15 ? 0 : Integer.parseInt(infos[5].trim()));
					float avg = (infos[9].endsWith("NaN") ? 0 : Float.parseFloat(infos[9].trim()));						
					//System.out.println("update statistics "+monitorString);
					mda.updateMonitorStat(instId, i+1, min, max, avg, count);
				}
				this.updating = false;
			}
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("update finished");
	}
	
	//call the updateStat() timely until stopped is set to true
	public void run(){
		//update statistics periodically
		stopped = false;
		while(!stopped){
			this.updateStat();
			ConfigParser parser = new ConfigParser();
			
			try {
				int updatetime = Integer.parseInt(parser.getElement("updatetime"));
				sleep(updatetime);
			} catch (InterruptedException e) {
				e.printStackTrace();
			} 
		}
	}
	
	//stop this monitor thread
	public boolean setStop()
	{	
		//try to stop the monitor for at most 10 times
		for(int i=0;i<10;i++)
		{
			if(!updating)
			{
				stopped = true;
				return true;
			}
			else
			{
				try {
					System.out.println("can not stop monitor service when updating");
					sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		return false;
	}
	
	public boolean resetStats(String InstanceId)
	{
		System.out.println("reset statistic of instance"+InstanceId);
		MonitorDAO mda = new MonitorDAO();
		if(mda.deleteMonitorStat(InstanceId))
			return true;
		return false;
	}
	
	public static void main(String[] args){
		MonitorService service = new MonitorService();
		service.run();
	}
}
